﻿using MediatR;
using S.Archives.Domain.S.ArchivesDto.Total;
using S.Archives.Infrstructre;
using S.Archives.Read.Api.Application.Command.Total;

namespace S.Archives.Read.Api.Application.CommandHandlers.Total
{
    /// <summary>
    /// 淘汰趋势
    /// </summary>
    public class EliminationTrendCommandHandler : IRequestHandler<EliminationTrendCommand, List<Nearly30DaysCloumnDto>>
    {
        private readonly DbHelper dbHelper;
        public EliminationTrendCommandHandler(DbHelper dbHelper)
        {
            this.dbHelper = dbHelper;
        }
        public async Task<List<Nearly30DaysCloumnDto>> Handle(EliminationTrendCommand request, CancellationToken cancellationToken)
        {
            var sql = "WITH Dates AS (  SELECT CONVERT(date, GETDATE()) AS DateValue  UNION ALL  SELECT CONVERT(date, DATEADD(day, -1, DateValue))  FROM Dates  WHERE DateValue >= DATEADD(day, -29, CONVERT(date, GETDATE()))  ) SELECT   Dates.DateValue AS CloumDate,   COALESCE(COUNT(EliminationModel.PhaseOutDate), 0) AS CloumCount FROM Dates LEFT JOIN EliminationModel   ON CONVERT(date, EliminationModel.PhaseOutDate) = Dates.DateValue  AND EliminationModel.DepartureState = 1  GROUP BY Dates.DateValue ORDER BY Dates.DateValue ASC;";
            return await dbHelper.GetListDataBySql<Nearly30DaysCloumnDto>(sql);
        }
    }
}
